<template>
  <div class="flex gap-2 w-[450px]">
    <el-input
      ref="InputRef"
      v-model="inputValue"
      class="w-20"
      :placeholder="props.placeholder"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
      :disabled="dynamicTags.length >= props.maxNum"
    />
    <el-button
      class="button-new-tag"
      plain
      @click="showInput"
      :disabled="dynamicTags.length >= props.maxNum"
    >
      添加
    </el-button>
    <el-text class="mx-1 w-[200px]" size="small"
      >最多添加{{ props.maxNum }}个</el-text
    >
  </div>
  <div class="flex w-full gap-2 mt-[10px]">
    <el-tag
      v-for="tag in dynamicTags"
      :key="tag"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
  </div>
</template>

<script lang="ts" setup>
import { nextTick, ref } from "vue";
import { ElInput } from "element-plus";
const props = defineProps({
  list: {
    type: Array,
    default: () => []
  },
  placeholder: {
    type: String,
    default: "请输入自定义标签"
  },
  maxNum: {
    type: Number,
    default: 5
  }
});
const inputValue = ref("");
const dynamicTags = ref(
  props.list.length <= 0 ? ["公益创投", "扶幼助困", "青少年活动"] : []
);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

const showInput = () => {
  inputVisible.value = true;
  nextTick(() => {
    InputRef.value!.input!.focus();
  });
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};
</script>
